import json
from datetime import datetime
from database_manager import get_db_connection
from config_manager import config


def get_standardized_symbol(symbol):
    """获取标准化的股票代码（去掉交易所后缀）"""
    return symbol.split('.')[0]


def get_cached_analysis(symbol):
    """从数据库获取缓存的分析结果"""
    conn = get_db_connection()
    if not conn:
        return None
    
    # 获取标准化的股票代码
    std_symbol = get_standardized_symbol(symbol)
    
    try:
        with conn.cursor() as cursor:
            # 查询时使用标准化的股票代码（去掉交易所后缀）
            cursor.execute("""
                SELECT * FROM stock_analysis_results 
                WHERE SUBSTRING_INDEX(symbol, '.', 1) = %s 
                ORDER BY created_at DESC 
                LIMIT 1
            """, (std_symbol,))
            result = cursor.fetchone()
            
            if result:
                created_at = result['created_at']
                current_time = datetime.now()
                
                # 比较日期是否相同（不考虑具体时间）
                if isinstance(created_at, datetime):
                    # 如果created_at已经是datetime对象
                    is_same_day = (created_at.date() == current_time.date())
                else:
                    # 如果created_at是字符串，需要先转换
                    try:
                        # 尝试各种可能的日期格式
                        formats = ['%Y-%m-%d', '%Y/%m/%d', '%Y%m%d']
                        created_date = None
                        for fmt in formats:
                            try:
                                created_date = datetime.strptime(str(created_at).split()[0], fmt).date()
                                break
                            except ValueError:
                                continue
                        
                        if created_date:
                            is_same_day = (created_date == current_time.date())
                        else:
                            # 如果所有格式都转换失败，则认为是非当天数据
                            is_same_day = False
                            print(f"无法解析日期格式: {created_at}")
                    except Exception as e:
                        # 如果发生任何异常，认为是非当天数据
                        is_same_day = False
                        print(f"日期比较异常: {e}")
                
                if is_same_day:
                    print(f"从缓存获取当天分析结果: {symbol}，创建日期: {created_at}")
                    # 转换indicators从JSON字符串到字典
                    if isinstance(result['indicators'], str):
                        result['indicators'] = json.loads(result['indicators'])
                    return result
                else:
                    print(f"缓存已过期（非当天数据）: {symbol}，创建日期: {created_at}")
        return None
    except Exception as e:
        print(f"查询缓存失败: {e}")
        return None
    finally:
        conn.close()


def save_analysis_to_db(symbol, analysis_result):
    """保存分析结果到数据库"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        with conn.cursor() as cursor:
            # 将indicators字典转换为JSON字符串
            indicators_json = json.dumps(analysis_result['indicators'])
            
            # 插入数据，保留原始symbol格式
            cursor.execute("""
                INSERT INTO stock_analysis_results 
                (symbol, stock_name, industry, indicators, analysis)
                VALUES (%s, %s, %s, %s, %s)
            """, (
                symbol,
                analysis_result.get('stock_name'),
                analysis_result.get('industry'),
                indicators_json,
                analysis_result.get('analysis')
            ))
        conn.commit()
        print(f"分析结果已保存到数据库: {symbol}")
        return True
    except Exception as e:
        print(f"保存到数据库失败: {e}")
        conn.rollback()
        return False
    finally:
        conn.close()
